<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\admin\model\finance\extract\Week;
use app\admin\model\finance\extract\Weeklog;
use app\admin\model\finance\extract\Books as book;
use think\Cookie;
//日记账
class Books extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $books_auth = ['all'=>0,'add'=>0,'edit'=>0,'del'=>0,'department'=>''];
   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $Api = new Api();
        //获取默认值
        $this->config = $Api->getConfig($Api->getDefault('Books'));
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new Week();
        $this->Booksmodel = new book();
        //退出
        //print_r($this->auth->logout());die; 
        //模拟登陆
        //$this->auth->IndexLogin('GaoZhenYu');
        //判断权限
        //print_r($this->auth->check('see/index'));die;
         if (!$this->auth->isLogin() || (!$this->auth->isLogin() && !ValueExists($this->request->action(),'login,oauth,index'))){
            header("Location:".$this->request->domain().'/index/books/login');
            //return redirect($this->request->domain().'/index/plan/login');
        }else{
              $this->books_auth =  check_books_public(1,$this->auth);
              if(!$this->books_auth) $this->error(__('请联系管理员'));
             // print_r(date('W',strtotime('2019-11-25')));die;
        }
      $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
      $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
      $this->view->assign("DefaultsTime", $start_time.','.$end_time);
      $this->view->assign("DefaultsDate", date('Y'));
      $this->view->assign("DefaultsDateM", date('m'));
      $this->view->assign("DefaultsDateW", GetYearWeekOne(date('Y'),$start_time)-1);
      $this->view->assign("DefaultsDateD", date('w')-1);
      $this->view->assign('books_auth',$this->books_auth);
    }

   
    public function index(){
        \think\Cookie::delete("books_auth");
       $this->auth->logout();

       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/books/login');
        
    }  
    public function lists() {
       header('Access-Control-Allow-Credentials:true');
       $this->view->assign('info','');
       if($this->books_auth['all']){
           //$dept_list = collection($dept_list)->toArray();
           $this->view->assign('dept_list',$this->model->getDepartmentList());
       }
        
     
       return $this->view->fetch();
    }
    //return [-1=>'初审驳回',-2=>'终审驳回',0=>'草稿',1=>'初审中',2=>'初审通过',3=>'终审中',4=>'终审完成'];
    public function lists_ajax(){
       header('Access-Control-Allow-Credentials:true');
        if ($this->request->isAjax()){
            $where = ' `status` not in(-1,0,1)';
            $sort = $this->request->get("sort", "start_time");
            $order = $this->request->get("order", "desc");
            $page = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $offset = $limit*$page;
              $time = $this->request->get("time", '');
              $year = $this->request->get("year", '');
            if($this->books_auth['all']){
                $department = $this->request->get("department", 0);
            
            }elseif($this->books_auth['add']){
                $department = $this->books_auth['department'];
                
            }
            if($department){
                $where .=" and `department` = ".$department."";
            }
            if($time){
                $time = explode(',', $time);
                $where .=" and `start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
            }
            if($year){
                $where .=" and `year` = '".$year."' ";
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
              //  print_r($this->model->getLastSql());die;
            foreach ($list as $row) {
                $row->visible(['id','department','name','start_time','end_time','year','month','week','status','status_desc','createtime','updatetime']);
            }
         
            $list = collection($list)->toArray();
        
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }   
    public function add($ids = 0){
      header('Access-Control-Allow-Credentials:true');
      if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
              // print_r($this->Booksmodel->getLastSql());die;
                $params['publish'] = $params['z_publish']  = \think\Session::get('admin')['userid'];
                try {
                    $result = $this->Booksmodel->save($params);
                    if ($result !== false) {
                       $this->success('','',$params['extract_week']);
                    } else {
                        $this->error($this->Booksmodel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $info = $this->model->where(['department'=>$this->books_auth['department'],'status'=>2])->count();
        if(!$info) $this->error('您所在的分公司还没有开会，请联系负责人');
        $this->view->assign('ids',$ids);
        return $this->view->fetch();
    }
    public function edit($ids = NULL,$id = 0){
      header('Access-Control-Allow-Credentials:true');
      $row = $this->Booksmodel->get($ids);
      if (!$row) $this->error(__('No Results were found'));
      $info = $this->model->get($row['extract_week']);
      if (!$info) $this->error(__('No Results were found'));
      if(!$this->books_auth['edit'] || $this->books_auth['department'] !=$info['department'])  $this->error("没有权限");
      if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                       $this->success('','',$params['extract_week']);
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('info',$info);
        $this->view->assign('row',$row);
        $this->view->assign('ids',$id);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function delete($ids = "")
    {
    
        if ($ids) {
            $pk = $this->Booksmodel->getPk();
            $list = $this->Booksmodel->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success('','',$list[0]['extract_week']);
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
   
    public function view($ids = NULL){
        $info = Week::get($ids);
        if(!$info) $this->error(__('No Results were found'));
        $Books = TableListSqlQuery('Books','`extract_week` = '.$ids.'');
        $weekarray=array("日","一","二","三","四","五","六"); 
        if(!empty($Books)){
            foreach($Books as $kk=>&$vv){
                $vv['time'] = date('Y-m-d',strtotime(TableField('Week','start_time',$vv['extract_week'])." +".$vv['day']." day"));
                $vv['week'] = '星期'.$weekarray[date("w",strtotime($vv['time']))];
                $vv['Books_view'] = TableListSqlQuery('Books_view','`extract_week` = '.$ids.' and `day` = '.$vv['day'].'');
            }
        }
        $this->view->assign('Books',$Books);
        $this->view->assign('info',$info);
        return $this->view->fetch('public_view_books');
    }
    public function login(){
        $app = Factory::work($this->config);
        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;
                    return redirect($this->request->domain().'/index/books/lists');
                }
            }
        }else{
            return redirect($this->request->domain().'/index/books/oauth');
        }
    }
   public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

  

}
